package com.mind.customer.handler.tongwei;

import com.alibaba.fastjson2.JSONArray;
import com.mind.customer.domain.vo.TaskResult;
import com.mind.customer.handler.common.CommonHandler;
import com.mind.customer.mapper.AjDatasourceMapper;
import com.mind.customer.mapper.AjObjectMapper;
import com.mind.customer.utils.datasource.ReflectionDao;
import com.mind.system.domain.AjDatasource;
import com.mind.system.domain.AjObject;
import com.mind.system.domain.AjTicketTask;
import com.mind.system.domain.vo.Field;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@Component
@Log4j2
public class DataSourceHandler {

    @Resource
    private AjObjectMapper objectMapper;

    @Resource
    private AjDatasourceMapper datasourceMapper;

    @Resource
    private CommonHandler commonHandler;

    @Resource
    private ReflectionDao reflectionDao;


    public TaskResult handler(AjTicketTask task) throws Exception{
        List<AjObject> ajObjectList = objectMapper.selectObjectList(new AjObject() {{
            setTicketType(task.getTicketType());
            setType("Datasource");
        }});
        for(AjObject ajObject : ajObjectList){
            AjDatasource ajDatasource = datasourceMapper.selectDatasourceById(ajObject.getSourceId());
            if (ajDatasource == null) {
                log.error("该对象{}, 没有找到数据源", ajObject.getName());
                continue;
            }
            JSONArray jsonArray = reflectionDao.queryAll(ajDatasource);
            JSONArray result = commonHandler.processField(task.getTicketType(), JSONArray.parseArray(ajObject.getFields(), Field.class), jsonArray);
            if (result != null)
                return new TaskResult(){{
                    setStatus(1);
                    setData(new HashMap<String, Object>(){{
                        put(ajObject.getName(), result);
                    }});
                    setOriginalData(new HashMap<String, Object>(){{
                        put(ajObject.getName(), jsonArray);
                    }});
                }};
        }
        return null;
    }
}
